//
//  DiscoverController.m
//  Mango
//
//  Created by lanou3g on 16/5/4.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "DiscoverController.h"
#import "LeftModel.h"
#import "DiscoverStarsModel.h"
#import "ReusableHeaderView.h"
#import "DiscoverCell.h"
#import "StarTableViewCell.h"
#import "InfoModel.h"
#import "InfoCell.h"
#import "MoreTableViewController.h"
#import "DetailViewController.h"
#import "ListTableViewController.h"
#import "SearchTableViewController.h"
#import "StarCollectionViewController.h"
#import "StarInfoViewController.h"


#define found_url @"http://api.app.happyjuzi.com/foundpage/home"

@interface DiscoverController ()<UITableViewDelegate,UITableViewDataSource,ReusableHeaderViewDelegate,StarTableViewCellDelegate,UISearchBarDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (strong, nonatomic) InfoModel *hots;
@property (strong, nonatomic) NSMutableArray *dataSource_finecolumns;   //精选栏目
@property (strong, nonatomic) NSMutableArray *dataSource_kols;          //媒体号
@property (strong, nonatomic) NSMutableArray *dataSource_stars;         //明星库

@property (strong, nonatomic) NSArray *titles;

@property (nonatomic, copy) NSString *currentSkinModel;//夜间模式

@end

@implementation DiscoverController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化数组
    self.hots                   = [InfoModel new];  //今日热榜
    self.dataSource_finecolumns = [NSMutableArray array];  //精选栏目
    self.dataSource_kols        = [NSMutableArray array];  //媒体号
    self.dataSource_stars       = [NSMutableArray array];  //明星库
    self.titles = @[@"今日热门",@"精选栏目",@"媒体号",@"明星库"];
    
    self.tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    

    [self.tableView registerNib:[UINib nibWithNibName:@"DiscoverCell" bundle:nil] forCellReuseIdentifier:@"discover"];
     [self.tableView registerNib:[UINib nibWithNibName:@"InfoCell" bundle:nil] forCellReuseIdentifier:@"InfoCell"];
    
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor colorWithRed:223/255.0 green:223/255.0 blue:223/255.0 alpha:0.7];
    
    
    
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, ScreenSizeW, 30)];
    self.navigationItem.titleView = searchBar;
    searchBar.delegate = self;
    searchBar.placeholder = @"搜索你感兴趣的内容";
   
    [self refreshData];
}


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkinModel) name:SkinModelDidChangedNotification object:nil];
    [self updateSkinModel];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark --private Method--更新皮肤模式 接到模式切换的通知后会调用此方法
-(void)updateSkinModel {
    self.currentSkinModel = [[NSUserDefaults standardUserDefaults] stringForKey:CurrentSkinModelKey];
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//夜间模式
        self.tableView.backgroundColor = [UIColor blackColor];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    } else {//日间模式
//        self.tableView.backgroundColor = [UIColor colorWithRed:223/255.0 green:223/255.0 blue:223/255.0 alpha:0.7];
    }
    [self.tableView reloadData];
}




// 搜索框
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    SearchTableViewController *searchVC = [[SearchTableViewController alloc]init];
    [self.navigationController pushViewController:searchVC animated:YES];
    return NO;
}


- (void)refreshData {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadDataFromServer)];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    [self.tableView.mj_header beginRefreshing];
}

- (void)loadDataFromServer {
    [self removeAllObjects];
    NSDictionary *dict = @{@"net":@"wifi",@"pf":@"ios",@"res":@"320x568",@"uid":@"3971854834692451",@"ver":@"2.11"};
    [[AFHTTPSessionManager manager]GET:found_url parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self parserDataWith:responseObject];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}
//移除数组中的元素
- (void)removeAllObjects {
    [self.dataSource_kols removeAllObjects];
    [self.dataSource_finecolumns removeAllObjects];
    [self.dataSource_stars removeAllObjects];
}

//解析数据
- (void)parserDataWith:(NSDictionary *)responseObject {
    NSDictionary *dataDict = responseObject[@"data"];
    //精选栏目
    NSArray *finecolumns = dataDict[@"finecolumns"];
    for (NSDictionary *dict in finecolumns) {
        LeftModel *model = [LeftModel new];
        [model setValuesForKeysWithDictionary:dict];
        [self.dataSource_finecolumns addObject:model];
    }
    //热榜
    NSDictionary *hotsDict = dataDict[@"hots"];
    [self.hots setValuesForKeysWithDictionary:hotsDict];
    //媒体号
    NSArray *kols = dataDict[@"kols"];
    for (NSDictionary *kolDict in kols) {
        LeftModel *kol = [LeftModel new];
        [kol setValuesForKeysWithDictionary:kolDict];
        [self.dataSource_kols addObject:kol];
    }
    //明星库
    NSArray *stars = dataDict[@"stars"];
    for (NSDictionary *starDict in stars) {
        DiscoverStarsModel *model = [DiscoverStarsModel new];
        [model setValuesForKeysWithDictionary:starDict];
        [self.dataSource_stars addObject:model];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return self.dataSource_finecolumns.count;
            break;
        case 2:
            return self.dataSource_kols.count;
            break;
        case 3:
            return 1;
            break;
        default:
            break;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 0:{
            InfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InfoCell"];
            cell.model = self.hots;
#pragma mark --private Method--更新皮肤模式
            if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//日间模式
                [cell updateToNightSkinMode];
            }else {
                [cell updateToDaySkinMode];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case 1:{
             DiscoverCell *cell = [tableView dequeueReusableCellWithIdentifier:@"discover"];
            cell.model = self.dataSource_finecolumns[indexPath.row];
            if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//日间模式
                [cell updateToNightSkinMode];
            }else {
                [cell updateToDaySkinMode];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case 2:{
            DiscoverCell *cell = [tableView dequeueReusableCellWithIdentifier:@"discover"];
            cell.model = self.dataSource_kols[indexPath.row];
            if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//日间模式
                [cell updateToNightSkinMode];
            }else {
                [cell updateToDaySkinMode];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case 3:{
            StarTableViewCell *cell = [StarTableViewCell cellWithTableView:tableView];
            cell.delegate = self;
            cell.dataSource = self.dataSource_stars;
            if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//日间模式
                [cell updateToNightSkinMode];
            }else {
                [cell updateToDaySkinMode];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
            
        default:
            break;
    }
    return nil;
}


//头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ReusableHeaderView *header = [ReusableHeaderView headerViewWithTableView:tableView];
    header.title = self.titles[section];
    header.moreBtn.tag = section;
    header.delegate = self;
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//日间模式
        [header updateToNightSkinMode];
    }else {
        [header updateToDaySkinMode];
    }
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return [InfoCell heightForHeadlineModelCell];
    }else if(indexPath.section == 3){
        return 163;
    }else {
        return 144;
    }
}

#pragma mark - ReusableHeaderViewDelegate
- (void)headerViewDidClickMoreBtn:(NSInteger)tag {
    if (tag == 1 || tag == 2) {
        MoreTableViewController *moreVC = [[MoreTableViewController alloc]init];
        moreVC.type = tag;
        [self.navigationController pushViewController:moreVC animated:YES];
    }
    if (tag == 0) {
        ListTableViewController *listVC = [[ListTableViewController alloc]init];
        listVC.type = @"今日热榜";
        [self.navigationController pushViewController:listVC animated:YES];
    }
    if (tag == 3) {
        StarCollectionViewController *starVC = [[StarCollectionViewController alloc]init];
        [self.navigationController pushViewController:starVC animated:YES];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BaseModel *model = nil;
    switch (indexPath.section) {
        case 0:{
            model = self.hots;
            break;
        }
        case 1:{
            model = self.dataSource_finecolumns[indexPath.row];
            break;
        }
        case 2:{
            model = self.dataSource_kols[indexPath.row];
            break;
        }
        default:
            break;
    }
    DetailViewController *detailVC = [[DetailViewController alloc]init];
    //判断是否是专题
    NSString *urlRoute = [model.urlroute componentsSeparatedByString:@"?"][0];
    if ([urlRoute isEqualToString:@"juzi://specialreport"]) {
        return;
    }
    detailVC.ID  = model.ID;
    detailVC.listmodel = model;
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - StarTableViewCellDelegate
- (void)didClickStarItemAtIndexPath:(NSIndexPath *)indexPath {
    DiscoverStarsModel *model = self.dataSource_stars[indexPath.row];
    StarInfoViewController *starInfoVC = [[StarInfoViewController alloc]init];
    starInfoVC.sid = model.ID;
    [self.navigationController pushViewController:starInfoVC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if (self.view.window == nil && [self isViewLoaded]) {
        self.view = nil;
    }
}
@end
